package com.yeu.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import com.yeu.model.Sms;
import com.yeu.util.ConnectionPool;
import com.yeu.util.SMSTool;

public class SmsAction extends ActionSupport implements ModelDriven<Sms>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Sms sms=new Sms();
	private Map<String, String> boolResult;
	private String eventId;
	
	public String getEventId() {
		return eventId;
	}

	public void setEventId(String eventId) {
		this.eventId = eventId;
	}

	public Sms getSms() {
		return sms;
	}
	
	public void setSms(Sms sms) {
		this.sms = sms;
	}
	
	public Map<String, String> getBoolResult() {
		return boolResult;
	}

	@Override
	public Sms getModel() {
		return this.sms;
	}

	@Override
	public String execute() throws Exception {
		boolResult=new HashMap<String, String>();
		Boolean flag=false;
		/*String pre=String.format("尊敬的%s老师，我是仰恩大学学院110指挥平台的工作人员。", sms.getName());
		if(SMSTool.getOpenState()==SMSTool.STATE.OPEN && SMSTool.getSendState()==SMSTool.STATE.NORMAL){
			if(SMSTool.sendMessage(sms.getAddr(), pre+sms.getText())){
				Date date=new Date();
				DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String newTime=format.format(date);
				String  sql="insert into MESSAGE (MESSAGEID,MESSAGEDATE,MESSAGEPHONE,MESSAGECONTENT,MESSAGETYPE,MESSAGENAME) values(INCREASE_SEQUENCE.nextval,?,?,?,?,?)";
				flag=ConnectionPool.executeUpdate(sql,newTime,sms.getAddr(),sms.getText(),"S",sms.getName()).get("RESULT");
			}
		}*/
		//System.out.println("sms.getAddr()="+sms.getAddr());
		//System.out.println("sms.getName()="+sms.getName());
        Credential cred = new Credential("AKID0qPikW1FCuLVO0MRFl10i8IBn8C6rPhn", "rSmx00pPsHahaEcowxsdCVfkhYEfrnSq");
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        SendSmsRequest req = new SendSmsRequest();
        /******************************************确定短信内容，准备发送***************/
        String[] templateParaSet = new String[] {"未知","未知","未知","未知","未知","未知"};
        String content = sms.getText();
        String[] items = content.split("。");
        if(items.length < 4) {
    		boolResult.put("total", Integer.toString(0));
    		boolResult.put("success",Integer.toString(0));
    		boolResult.put("failed",Integer.toString(0));
    		return "boolResult";
        }
        String[] item0_parts = items[0].split("，");
        templateParaSet[0] = item0_parts[0];
        templateParaSet[1] = item0_parts[1].substring(0,item0_parts[1].length() - 2);
        String[] item1_parts = items[1].split("，");
        if(item1_parts.length == 2) {
        	for(int i = 0; i < 2; i++)
        		 templateParaSet[i + 2 ] = item1_parts[i].substring(item1_parts[i].indexOf("：") + 1);
        	templateParaSet[4] = "";
        }else if (item1_parts.length == 3) {
        	for(int i = 0; i < 2; i++)
       		     templateParaSet[i + 2 ] = item1_parts[i].substring(item1_parts[i].indexOf("：") + 1);
        	templateParaSet[4] = item1_parts[2].substring(item1_parts[2].indexOf("：")+1);
        	
        }
        
/*        System.out.println("："+ items[2].indexOf("：") + 1);
        System.out.println(":"+ items[2].indexOf(":") + 1);*/

        templateParaSet[5] = items[2].substring(items[2].indexOf("：") + 1);
       
/*        for(String s: templateParaSet) {
        	System.out.println(s);
        }*/
        
        req.setTemplateParamSet(templateParaSet);
        /*****************************************************************************/
        /********设置群发号码和其它参数***********************/
		String addr = sms.getAddr();
		//addr = addr.substring(0,addr.length() - 1);
		String address[] = addr.split(",+\\s*");
		req.setPhoneNumberSet(address);
        req.setSmsSdkAppId("1400570591");
        req.setSignName("仰恩大学校园110");
        req.setTemplateId("1117195");
		/*****************************************************************************/
		/****************发送短信并检查结果********************************************/
        SendSmsResponse resp = client.SendSms(req);
        SendStatus[] st = resp.getSendStatusSet();
        Boolean successCount[] = new Boolean[st.length];
        for(int i = 0; i < st.length; i++) {
        	if(st[i].getCode().equalsIgnoreCase("Ok"))
        		successCount[i] = true;
        	else
        		successCount[i] = false;
        }
        
		//String name = sms.getName();
		//name = name.substring(0,name.length() - 1);
		//String names[] = name.split(",+\\s*");
		//System.out.println(eventId);
		/*for(String s:address){
			System.out.println(s);
		}*/
		
/*		Boolean successCount[] = new Boolean[address.length];
		if(SMSTool.getOpenState()==SMSTool.STATE.OPEN && 
				SMSTool.getSendState()==SMSTool.STATE.NORMAL){
			for(int i = 0; i < address.length; i++){
				successCount[i] = SMSTool.sendMessage(address[i], sms.getText());
				if(successCount[i]){
					Date date=new Date();
					DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String newTime=format.format(date);
					String  sql="insert into MESSAGE (MESSAGEID,MESSAGEDATE,MESSAGEPHONE,MESSAGECONTENT,MESSAGETYPE,MESSAGENAME,EVENTID) values(INCREASE_SEQUENCE.nextval,?,?,?,?,?,?)";
					if(i < names.length)
						name = names[i];
					else
						name = "";
					ConnectionPool.executeUpdate(sql,newTime,address[i],sms.getText(),"S",name,eventId);
				}
			}
			
		}*/
		int success = 0;
		int failed = 0;
		for(int i = 0; i < successCount.length; i++){
			if(successCount[i]){
				success++;
			}else{
				failed++;
			}
		}
		boolResult.put("total", Integer.toString(successCount.length));
		boolResult.put("success",Integer.toString(success));
		boolResult.put("failed",Integer.toString(failed));
		return "boolResult";
	}
}
